new Vue({
    el: '#app',
    data: {
        product: {
            id: '',
            name: '',
            image: '',
            price: 0,
            description: '',
            specs: [],
        },
        comments: [],
        quantity: 1,
        // 弹窗
        showSuccessModal: false,
        // 弹窗消失的时间
        successModalTimer: null,
    },
    methods: {
        getProductIdFromUrl() {
            const params = new URLSearchParams(window.location.search);

            return params.get('commodityId');
        },
        fetchProduct() {
            const id = this.getProductIdFromUrl();
            if (!id) return;
            // 获取商品详情
            $.ajax({
                url: 'http://localhost:8080/commodity/findCommodityById',
                type: 'GET',
                headers: { 'token': `${localStorage.getItem('token') || ''}` },
                data: { id: id },
                dataType: 'json',
                success: (res) => {
                    if (res.code === 200) {
                        this.product = res.data;
                        this.product.image = '\\' + res.data.commodityPicture[0].commodityImageUrl.match(/photo[\\\\/].+$/)[0]
                    } else {
                        alert('商品信息加载失败');
                    }
                },
                error: () => {
                    alert('商品信息加载失败');
                }
            });
        },
        fetchComments() {
            // const id = this.getProductIdFromUrl();
            // if (!id) return;
            // // 获取商品评论
            // $.ajax({
            //     url: '/api/product/comments',
            //     type: 'GET',
            //     data: { id },
            //     dataType: 'json',
            //     success: (res) => {
            //         if (res.code === 200) {
            //             this.comments = res.data;
            //         } else {
            //             this.comments = [];
            //         }
            //     },
            //     error: () => {
            //         this.comments = [];
            //     }
            // });
        },
        // 数量减
        decreaseQuantity() {
            if (this.quantity > 1) this.quantity--;
        },
        // 数量加
        increaseQuantity() {
            this.quantity++;
        },
        addToCart() {
            // 加入购物车逻辑
            $.ajax({
                url: 'http://localhost:8080/cart/addCommodityToCart',
                type: 'POST',
                headers: { 'token': `${localStorage.getItem('token') || ''}` },
                data: {
                    userId: localStorage.getItem('userId'),
                    productId: this.product.commodityId,
                    quantity: this.quantity
                },
                success: (res) => {
                    if (res.code === 200) {
                        this.showSuccessModal = true;
                        if (this.successModalTimer) {
                            clearTimeout(this.successModalTimer);
                        }
                        // 3秒后弹窗自动关闭
                        this.successModalTimer = setTimeout(() => {
                            this.showSuccessModal = false;
                        }, 3000);
                    } else {
                        console.log('加入购物车失败：' + res.message);
                    }
                },
                error: () => {
                    alert('加入购物车失败');
                }
            });
        },
        // 点击立即购买
        buyNow() {
            // 准备购买的商品信息，发送包含商品ID和数量的单个对象
            const commodityId = this.product.commodityId;
            console.log(commodityId);

            // 创建一个对象来存储商品ID和数量
            const dataToSend = {};
            dataToSend[this.product.commodityId] = this.quantity;

            // 将对象转换为 JSON 字符串
            const dataToSendJSON = JSON.stringify(dataToSend);

            // 发送AJAX请求到后台，准备订单并获取订单标识符
            $.ajax({
                url: 'http://localhost:8080/cart/buyCommodity?userId=' + localStorage.getItem('userId'),
                type: 'POST',
                contentType: 'application/json',
                data: dataToSendJSON,
                dataType: 'json',
                headers: { 'token': `${localStorage.getItem('token') || ''}` },
                success: (res) => {
                    if (res.code === 200 ) {
                        // 订单准备成功，跳转到订单确认页
                        window.location.href = `order-confirm-test.html?orderId=${res.data}`;
                    } else {
                        alert('直接购买失败：' + (res.message || '未知错误'));
                    }
                },
                error: (xhr, status, error) => {
                    alert('网络错误，直接购买失败。');
                    console.error(status, error);
                }
            });
        },
        // 点击去购物车直接跳转到购物车
        goToCart() {
            if (this.successModalTimer) {
                clearTimeout(this.successModalTimer);
            }
            this.showSuccessModal = false;
            window.location.href = 'cart.html';
        }
    },
    created() {
        this.fetchProduct();
        this.fetchComments();
    }
}); 